package cn.msn.org.service.impl;

import cn.msn.basic.exception.BusinessException;
import cn.msn.basic.service.impl.BaseServiceImpl;
import cn.msn.basic.util.BaiduAuditUtils;
import cn.msn.basic.util.Md5Utils;
import cn.msn.basic.util.StrUtils;
import cn.msn.org.domain.Employee;
import cn.msn.org.domain.Shop;
import cn.msn.org.domain.ShopAuditLog;
import cn.msn.org.dto.ShopDto;
import cn.msn.org.mapper.EmployeeMapper;
import cn.msn.org.mapper.ShopAuditLogMapper;
import cn.msn.org.mapper.ShopMapper;
import cn.msn.org.service.IShopService;
import cn.msn.user.domain.Logininfo;
import cn.msn.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    @Transactional
    public void settlement(Shop shop) {
        //一：校验 1.空值校验(写一个) 2.格式通过正则表达式（不写） 3.校验是否入驻过
        // 3.确认密码校验（不写） - 前端已经校验了后端还有校验，前端js代码校验可能会被跳过
        //空值校验 - a.直接使用字符串的方法 b.使用apache提供的lang3包 c.使用其他工具类
        if (StringUtils.isEmpty(shop.getName())) {
            throw new BusinessException("店铺名称不能为空");
        }
        Shop dbShop = shopMapper.loadByNameAndAddress(shop);
        //说明根据名称和地址找到了 - 这个店铺注册过了
        if(dbShop != null){
            throw  new BusinessException("店铺已经入驻，请直接登录!如果忘记密码，请联系管理员!!!");
        }
        // 百度AI只能审核
        Boolean b1 = BaiduAuditUtils.TextCensor(shop.getName() + shop.getAddress());
        if (!b1) {
            throw new BusinessException("店铺名称和地址不符合社会主义核心价值观");
        }
        String url = "http://123.207.27.208" + shop.getLogo();
        Boolean b2 = BaiduAuditUtils.ImgCensor(url);
        if (!b2) {
            throw new BusinessException("图片不符合规范");
        }


        //二：添加管理员信息 - 添加了之后就可以获取自增ID
        Employee admin = shop.getAdmin();

        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(admin.getPassword()+salt);
        admin.setSalt(salt);
        admin.setPassword(md5Pwd);
        employeeMapper.save(admin);

        //三：将自增id设置到t_shop的admin_id
        shop.setAdminId(admin.getId());
        shopMapper.save(shop);

        // 保存登录信息t_logininfo
        Logininfo logininfo = employee2Logininfo(admin);
        logininfoMapper.save(logininfo);

        admin.setShop_id(shop.getId());
        //2.6.将登录信息的id更新到t_employee中
        admin.setLogininfo_id(logininfo.getId());
        //2.7.修改员工信息 - 修改shop_id和logininfo_id
        employeeMapper.update(admin);
    }
    public Logininfo employee2Logininfo(Employee employee){
        Logininfo logininfo = new Logininfo();

        BeanUtils.copyProperties(employee,logininfo);
        //当前对象是店铺管理员
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    @Transactional
    public void auditPass(ShopAuditLog shopAuditLog) throws MessagingException {
        //1.修改状态：1-2
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(2);
        shopMapper.update(shop);

        //2.添加审核日志
        shopAuditLog.setState(2);
        shopAuditLog.setAuditId(350L);
        shopAuditLogMapper.save(shopAuditLog);

        //3.发送激活邮件
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom("329994750@qq.com");
        //给管理员发送邮件
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        helper.setTo(employee.getEmail());
        helper.setSubject("审核通过!!!");
        helper.setText("<h1>店铺激活邮件!!!</h1><h3><a href='http://localhost:8080/shop/active/"+shopAuditLog.getShopId()
                +"'>点击该链接激活店铺</a></h3>",true);
        javaMailSender.send(message);
    }

    @Override
    @Transactional
    public void auditReject(ShopAuditLog shopAuditLog) throws MessagingException {
        //1.修改状态：1-4
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(4);
        shopMapper.update(shop);

        //2.添加审核日志
        shopAuditLog.setState(4);
        shopAuditLog.setAuditId(350L);
        shopAuditLogMapper.save(shopAuditLog);

        //3.发送激活邮件
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom("329994750@qq.com");
        //给管理员发送邮件
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        helper.setTo(employee.getEmail());
        helper.setSubject("店铺激活邮件!!!");
        helper.setText("<h1>店铺激活失败!!!</h1><h3><a href='http://localhost:8081/#/register'>点击该链接重新入驻</a></h3>",true);
        javaMailSender.send(message);
    }
    @Override
    public List<ShopDto> getCountByState() {
        return shopMapper.getCountByState();
    }

    @Override
    public void getActive(Long id) throws MessagingException {
        Shop shop = shopMapper.loadById(id);
        shop.setState(3);
        shopMapper.update(shop);
        //3.发送激活邮件
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom("329994750@qq.com");
        //给管理员发送邮件
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        helper.setTo(employee.getEmail());
        helper.setSubject("店铺激活邮件!!!");
        helper.setText("激活成功");
        javaMailSender.send(message);
    }
}
